<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>在线设备监控</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
	href="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/css/bootstrap.min.css">
<script
	src="http://cdn.static.runoob.com/libs/jquery/2.1.1/jquery.min.js"></script>
<script
	src="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">

</head>

<body>
	<div style="background-color: #262626;">
		<label id="times" style="color: yellowgreen;"></label> <label
			id="status" style="color: yellow;display: block;">当前状态</label>
	</div>
	<div class="container-fluid">

		<div class="row-fluid">
			<div class="span12">
				<h3 id="deviceCount" class="text-center" style="color: red;"></h3>
				<h3 id="maxCount" class="text-center" style="color: green;"></h3>
				<table class="table table-hover table-bordered">
					<thead>
						<tr>
							<th>编号</th>
							<th>手机型号</th>
							<th>设备标识</th>
							<th>用户</th>
							<th>登入时间</th>
							<th>状态</th>
						</tr>
					</thead>
					<tbody id="container">
					</tbody>
				</table>
			</div>
		</div>
	</div>
</body>
<script type="text/javascript">
	var timestamp = (Date.parse(new Date())).toString();
	var tt = parseInt(timestamp.substring(0, 10));
	function t()
	{
		now=new Date((tt+i+28800)*1000);
		i++;
		document.getElementById("times").innerHTML="当前时间：" + now.toUTCString();
	}
	var i=0;
	setInterval("t()",1000);
	
	var ST_MD = 0; 
	var ED_MD = 1; 
	var CT_MD = 2; 
	var LT_MD = 3; 
	
	var CLIENT_OPEN_LIGHT = 0;
	var CLIENT_OPEN_LOG = 1;
	var CLIENT_CLOSE_APP = 2;
	
	var ST_MD_RESP = "ws-ss-sc"; 
    var ED_MD_RESP = "ws-se-sc"; 
    
    var CT_MD_RESP = "ws-ct-sc"; 
    var CT_MAXMD_RESP = "ws-maxct"; 
    var LT_MD_RESP = "ws-list-sc"; 
    
	var establish = false;
	var prepare_list = false;
	var prepare_count = false;
	var prepre_maxcount = false;
	
    var websocket = null;
    //判断当前浏览器是否支持WebSocket
    if ('WebSocket' in window) {
        websocket = new WebSocket("ws://119.23.35.212:8080/MavenDemo/websocket");
        //websocket = new WebSocket("ws://localhost:8080/MavenDemo/websocket");
    }else {
        alert('当前浏览器 Not support websocket')
    }

    //连接发生错误的回调方法
    websocket.onerror = function () {
        setMessageInnerHTML("error");
        establish = false;
        prepare_list = false;
        prepare_count = false;
    };

    //连接成功建立的回调方法
    websocket.onopen = function () {
        setMessageInnerHTML("连接成功");
        send(ST_MD);
    }

    //接收到消息的回调方法
    websocket.onmessage = function (event) 
    {
    	var resp = event.data; 
    	console.info(resp);
    	if(ST_MD_RESP == resp)
    	{
    		establish = true;
    		send(LT_MD);
    		send(CT_MD);
    	}else if(LT_MD_RESP == resp)
    	{
    		prepare_list = true;
    	}else if(CT_MD_RESP == resp)
    	{
    		prepare_count = true;
    	}else if(CT_MAXMD_RESP == resp)
    	{
    		prepare_maxcount = true;
    	}
    	
    	try{
	    	if(establish)
	    	{
	    		if(prepare_list)
	    		{
	    			var respBean = $.parseJSON(resp);
	    			var deviceList = respBean.data;
	    			console.info(deviceList);
	    			$("#container").html("");
	    			for (var i = 0; i < deviceList.length; i++)
	    			{
	    				var index = i+1;
	    				var token = deviceList[i].token;
	    				var device = deviceList[i].device;
	    				var userName = deviceList[i].userName;
	    				var logTime = deviceList[i].logTime;
	    				var sid = deviceList[i].seesionId;
	    				buildTable(index, token, device, userName, logTime,sid);
	    			}
	    			prepare_list = false;
	    		}
	    		if(prepare_count)
	    		{
	    			var respCount = $.parseJSON(resp);
	    			var count = respCount.count;
	    			document.getElementById('deviceCount').innerHTML = "当前在线客户端: "+count; 
	    			prepare_count = false;   
	    		}
	    		if(prepare_maxcount)
	    		{
	    			var respCount = $.parseJSON(resp);
	    			var max = respCount.maxDevice;
	    			var time = respCount.time;
	    			document.getElementById('maxCount').innerHTML = "在线设备峰值: "+max + "<><>峰值时间：" + time; 
	    			prepare_maxcount = false;  
	    		}
	    	}
    	}catch (err){}
    	
    }

    //连接关闭的回调方法
    websocket.onclose = function () {
        setMessageInnerHTML("连接关闭");
        prepare_list = false;
        prepare_count = false;
    }

    //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
    window.onbeforeunload = function () {
        closeWebSocket();
    }

    //将消息显示在网页上
    function setMessageInnerHTML(innerHTML) {
        document.getElementById('status').innerHTML = innerHTML;
    }

    //关闭WebSocket连接
    function closeWebSocket() {
    	send(ED_MD);
        websocket.close();
    }

    function send(cmdd) 
    {
    	switch(cmdd)
    	{
    		case 0:
    			 websocket.send("ws-ss");
    		break;
    		case 1:
    			 websocket.send("ws-se");
    		break;
    		case 2:
    			 websocket.send("ws-ct");
    		break;
    		case 3:
    			 websocket.send("ws-list");
    		break;
    	}
    }
    
    function buildTable(index, token, device, userName, logTime, sessionid)
    {
    	var ht = "<tr>"+
	    			"<th>"+index+"</th>"+
	    			"<th>"+device+"</th>"+
	    			"<th>"+token+"</th>"+
	    			"<th>"+userName+"</th>"+
	    			"<th>"+logTime+"</th>"+
	    			"<th hidden>"+sessionid+"</th>"+
	    			"<th>"+
	    				"<div class='btn-group'>"+
							  "<button type='button' class='btn btn-danger dropdown-toggle' data-toggle='dropdown' aria-haspopup='true' aria-expanded='false'>"+
							    "客户端操作 <span class='caret'></span>"+
							  "</button>"+
							  "<ul class='dropdown-menu'>"+
							    "<li><a href='javascript:void(0);' onclick='openLight(this);return false'>开灯</a></li>"+
							    "<li><a href='javascript:void(0);' onclick='openLog(this);return false'>日志开关</a></li>"+
							    "<li><a href='javascript:void(0);' onclick='exitApp(this);return false'>退出app</a></li>"+
							  "</ul>"+
						"</div>"+
	    			"</th>"+
				"</tr>"
    	$("#container").append(ht);
    }
    
    function openLight(obj)
    {
    	var sid = $(obj).parent()
    			.parent()
    			.parent()
    			.parent()
    			.prev().text();
    	websocket.send("cli-"+CLIENT_OPEN_LIGHT+"@"+sid);
    }
    
    function openLog(obj)
    {
    	var sid = $(obj).parent()
    			.parent()
    			.parent()
    			.parent()
    			.prev().text();
    	websocket.send("cli-"+CLIENT_OPEN_LOG+"@"+sid);
    }
    
    function exitApp(obj)
    {
    	var sid = $(obj).parent()
    			.parent()
    			.parent()
    			.parent()
    			.prev().text();
    	websocket.send("cli-"+CLIENT_CLOSE_APP+"@"+sid);
    }
</script>
</html>
